<?php

namespace Services\Sys\Models;

use Helpers\BaseModel;
use Modules\Power;
use Admin\Models\group\XhsysGrouppower;
use Admin\Models\sys\XhsysTree;

class XhsysPower extends BaseModel
{

    /**
     *
     * @var integer
     */
    public $iPowerId;

    /**
     *
     * @var integer
     */
    public $iNodeId;

    /**
     *
     * @var string
     */
    public $sPowerTag;

    /**
     *
     * @var integer
     */
    public $bPowerMain;

    /**
     *
     * @var string
     */
    public $sPowerName;

    /**
     *
     * @var integer
     */
//    public $bPowerExtra;

    /**
     *
     * @var string
     */
    public $sExtraUrl;

    /**
     * Initialize method for model.
     */
    public function initialize()
    {
        $this->useDynamicUpdate(true);
    }

    /**
     * Returns table name mapped in the model.
     *
     * @return string
     */
    public function getSource()
    {
        return 'XHSys_Power';
    }

    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhsysPower[]|XhsysPower|\Phalcon\Mvc\Model\ResultsetInterface
     */
    public static function find($parameters = null)
    {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhsysPower|\Phalcon\Mvc\Model
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }

    /**
     * 根据内容新增权限记录，权限值与id一致
     *
     * @param $data
     * @param bool|false $mainPower
     * @return bool
     *
     * create by ck 20160824
     * modify by ck 20160902    增加扩展权限及URL
     * modify by ck 20161013    简化
     * modify by ck 20170406    去除iPowerValue
     */
    public static function createRecord($data, $mainPower = false)
    {
        $obj = new self;
        $obj->assign($data);
        $obj->bPowerMain = $mainPower ? 1 : 0;
        if (!$obj->save()) {
            return false;
        }
        return true;
    }

    /**
     * @param array $navNodes
     * @param null $treeStr
     * @param $userId
     * @param $view
     * @return null|string
     *
     * create by ck 20160829    创建权限树，通过memcache缓存
     * modify by ck 20160830    根据用户ID，判断是否已有权限，有则默认选中，删除memcache缓存
     * modify by ck 20181031    自身无权限则不展示
     */
    public static function createPowerTree($navNodes = [], $treeStr = null, $userId = 0, $view = false)
    {
        if (!$navNodes) {
            $navNodes = XhsysTree::createNavNode('', true);
        }
        $liStr = '';
        if (!$treeStr) {
            $treeStr .= '<div class="tree-view-menu-list font-16"><ul class="font-16">';
            $treeStr .= self::createPowerTree($navNodes, $treeStr, $userId, $view);
            $treeStr .= '</ul></div>';
            return $treeStr;
        }
        foreach ($navNodes as $navNode) {
            if (!isset($navNode['sPowerTag'])) {
                continue;
            }
            //自身无权限则不展示
            if (!Power::exist($navNode['sPowerTag'])) {
                continue;
            }
//            if(!isset($navNode['iPowerValue'])) continue;
            $liCla = !empty($navNode['oChildNode'])
                ? ' class="openable' . ($navNode == end($navNodes) ? ' last-link' : '') . '"'
                : ($navNode == end($navNodes) ? ' class="last-link"' : '');
            $inIcon = !empty($navNode['oChildNode'])
                ? '<i class="fa fa-folder m-right-xs folder-icon"></i>'
                : '<i class="fa fa-file m-right-xs"></i>';
//            $ckdStr = XhsysUserpower::checkUserPowerByValue($userId, $navNode['iPowerValue']) ? 'checked="checked"' : '';
//            $ckdStr = XhsysUserpower::checkUserPowerByTag($userId, $navNode['sPowerTag'], $view) ? 'checked="checked"' : '';
            $ckdStr = Power::exist($navNode['sPowerTag'], $userId, $view ? null : 'user') ? 'checked="checked"' : '';
            $liStr .= '<li' . $liCla . '>';
//            $liStr .= '<input type="checkbox" name="powerValue[]" value="'. $navNode['iPowerValue'] .'" ' . $ckdStr . ' />';
            $liStr .= '<input type="checkbox" name="powerTag[]" value="' . $navNode['sPowerTag'] . '" ' . $ckdStr . ' />';
            $liStr .= "<a nodeId='{$navNode['iNodeId']}'>";
            $liStr .= $inIcon;                                              //添加节点图片
            $liStr .= $navNode['sNodeName'];
            $liStr .= '</a>';
            $liStr .= isset($navNode['oPowerNode'])
                ? self::createPowerCheckbox($navNode['oPowerNode'], $userId, $view ? null : 'user')
                : '';
            $liStr .= !empty($navNode['sExtraUrl']) ? "<a extra='{$navNode['sExtraUrl']}'>扩展权限</a>" : '';
            $liStr .= !empty($navNode['oChildNode'])
                ? ('<ul class="subtree">' . (
                        !empty($navNode['oChildNode'])
                        ? self::createPowerTree($navNode['oChildNode'], $liStr, $userId, $view)
                        : ''
                    ) .
                    '</ul>')
                : '';
            $liStr .= '</li>';
        }
        return $liStr;
    }

    /**
     * 根据权限节点创建复选框
     *
     * @param $powerNodes
     * @param $id
     * @param $type
     * @return string
     *
     * create by ck 20160829
     * modify by ck 20160830    根据用户ID，判断是否已有权限，有则默认选中
     * modify by ck 20171107    可根据组id判断
     * modify by ck 20181031    自身无权限则跳过
     */
    public static function createPowerCheckbox($powerNodes, $id, $type = null)
    {
        $liStr = '';
        foreach ($powerNodes as $powerNode) {
            if (!Power::exist($powerNode['sPowerTag'])) {
                continue;
            }
//            $isChecked = ($isGroup ? XhsysGrouppower::checkPowerByTag($id, $powerNode['sPowerTag']) : XhsysUserpower::checkUserPowerByTag($id, $powerNode['sPowerTag']))
//            $isChecked = ($isGroup ? XhsysGrouppower::checkPowerByTag($id, $powerNode['sPowerTag']) : UserPower::checkUserPower($powerNode['sPowerTag'], $id, 'group'))
            $isChecked = Power::exist($powerNode['sPowerTag'], $id, $type)
                ? 'checked' : '';
            $liStr .= "<label><input type='checkbox' name='powerTag[]' value='{$powerNode['sPowerTag']}' {$isChecked} />{$powerNode['sPowerName']}</label>";
        }
        return $liStr;
    }

    /**
     * 根据用户组id创建权限树
     *
     * @param $groupId
     * @param array $navNodes
     * @param null $treeStr
     * @return null|string
     *
     * create by ck 20171107
     */
    public static function createGroupPowerTree($groupId, $navNodes = [], $treeStr = null)
    {
        if (!$navNodes) {
            $navNodes = XhsysTree::createNavNode('', true);
        }
        $liStr = '';
        if (!$treeStr) {
            $treeStr .= '<div class="tree-view-menu-list font-16"><ul class="font-16">';
            $treeStr .= self::createGroupPowerTree($groupId, $navNodes, $treeStr);
            $treeStr .= '</ul></div>';
            return $treeStr;
        }
        foreach ($navNodes as $node) {
            if (!isset($node['sPowerTag'])) {
                continue;
            }
            $liClass = [];
            if (!empty($node['oChildNode'])) {
                $liClass[] = 'openable';
            }
            if ($node == end($navNodes)) {
                $liClass[] = 'last-link';
            }
            $liClass    = implode(' ', $liClass);

            $icon       = !empty($node['oChildNode']) ? '<i class="fa fa-folder m-right-xs folder-icon"></i>' : '<i class="fa fa-file m-right-xs"></i>';
            $isChecked  = XhsysGrouppower::checkPowerByTag($groupId, $node['sPowerTag']) ? 'checked' : '';
            $liStr .= "<li class='{$liClass}'>";
            $liStr .= "<input type='checkbox' name='powerTag[]' value='{$node['sPowerTag']}' {$isChecked} />";
            $liStr .= "<a nodeId='{$node['iNodeId']}'>{$icon}{$node['sNodeName']}</a>";
            $liStr .= isset($node['oPowerNode']) ? self::createPowerCheckbox($node['oPowerNode'], $groupId, 'group') : '';

            //add by ck 20180503
            $liStr .= !empty($node['sExtraUrl']) ? "<a extra='{$node['sExtraUrl']}'>扩展权限</a>" : '';

            if (!empty($node['oChildNode'])) {
                $liStr .= '<ul class="subtree">' . self::createGroupPowerTree($groupId, $node['oChildNode'], $liStr) .'</ul>';
            }
            $liStr .= '</li>';
        }
        return $liStr;
    }

}
